package com.ctbri.containerindepth;

import java.util.List;

import com.ctbri.util.TextFile;

class AssociativeArray2<K, V> {
	private Object[][] pairs;
	private int index = 0;
	public AssociativeArray2(int length) {
		pairs = new Object[length][2];
	}
	
	public void put(K key, V value) {
		for(int i = 0; i < index; i++) {
			if(pairs[i][0].equals(key)){
				pairs[i] = new Object[]{key, value};
				return;
			}
		}
		if(index >= pairs.length)
			throw new ArrayIndexOutOfBoundsException();
		pairs[index++] = new Object[]{key, value};
	}
	
	@SuppressWarnings("unchecked")
	public V get(K key) {
		for(int i = 0; i < index; i++)
			if(key.equals(pairs[i][0]))
				return (V)pairs[i][1];
		return null;
	}
	
	public String toString() {
		StringBuilder result = new StringBuilder();
		for(int i = 0; i < index; i++) {
			result.append(pairs[i][0].toString());
			result.append(" : ");
			result.append(pairs[i][1].toString());
			if(i < index - 1)
				result.append("\n");
		}
		return result.toString();
	}
}
	
public class Ex13 {
	public static void main(String[] args) {
		List<String> words = new TextFile
				("D:/Java/workspace/enterprise_gateway/WebContent/rtdata.jsp", "\\W+");
		AssociativeArray2<String, Integer> map = new AssociativeArray2<>(words.size());
		for(String word : words) {
			Integer num = map.get(word);
			if(num == null)
				map.put(word, 1);
			else
				map.put(word, ++num);
		}
		System.out.println(map);
	}
}
